package com.wuzhi.shop.auth.controller;


import com.wuzhi.common.constant.AuthServerConstant;
import com.wuzhi.common.exception.BizCodeEnum;
import com.wuzhi.common.utils.R;
import com.wuzhi.shop.auth.feign.MemberFeignService;
import com.wuzhi.shop.auth.feign.ThirdPartFeignService;
import com.wuzhi.shop.auth.vo.UserLoginVo;
import com.wuzhi.shop.auth.vo.UserRegisterVo;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Controller
public class  LoginController {
    //调用第三方服务的短信验证码，提交一个电话
    @Autowired
    ThirdPartFeignService thirdPartFeignService;
    //调用redis
    @Autowired
    StringRedisTemplate redisTemplate;

//    调用member的注册服务
    @Autowired
    MemberFeignService memberFeignService;

    @ResponseBody
    @GetMapping("/sms/sendcode")
    public R sendCode(@RequestParam("phone") String phone) {

        String redisCode = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
        if (!StringUtils.isEmpty(redisCode)) {
            long l = Long.parseLong(redisCode.split("_")[1]);
            //            60s内不能重发
            if (System.currentTimeMillis() - l < 60000) {
                return R.error(BizCodeEnum.SMS_CODE_EXCEPTION.getCode(), BizCodeEnum.SMS_CODE_EXCEPTION.getMsg());
            }
        }

//        1.接口防刷
//        2.验证码再次校验：redis: sms:code:13882974942 -> 223344
//        随机生成验证码
        String code = UUID.randomUUID().toString().substring(0, 5) + "_" + System.currentTimeMillis();
//        redis缓存验证码10分钟，防止手机在60s内再次发送验证码。
        redisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone, code, 10, TimeUnit.MINUTES);
//        将电话和生成的验证码发给第三方的验证服务，服务利用手机和验证码给用户
        code = code.split("_")[0];
        thirdPartFeignService.sendCode(phone, code);
        return R.ok();
    }

//    RedirectAttributes重定向带上数据
//    TODO 分布式session的问题。
//    点击注册进行校验，成功进入登录页面进行登录；@Valid进行数据校验。
    @PostMapping(value = "/register")
    public String register(@Valid UserRegisterVo vo, BindingResult result, RedirectAttributes redirectAttributes){
//        1.如果传入的vo不符合要求，返回注册页面，并且返回错误提示
        if(result.hasErrors()){
            Map<String,String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            redirectAttributes.addFlashAttribute("errors",errors);
            //            校验出错,回到注册页，并且返回提示
            return "redirect:http://auth.wuzhishop.com/reg.html";
        }

//        2.调用shop-member的服务进行真正的注册，对比验证码，写入数据库
        String code = vo.getCode();
        String s = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
        if(!StringUtils.isEmpty(s)){
//            2.1传入的code与redis中的验证码一样就注册成功
            if(code.equals(s.split("_")[0])){
//                删除redis中的验证码
                redisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
//              TODO 调用远程服务写入数据库，跳转到首页
                R r = memberFeignService.register(vo);
                if(r.getCode() ==0){
                    return "redirect:http://auth.wuzhishop.com/log.html";
                }else {
                 redirectAttributes.addFlashAttribute("registerErrors", "注册错误");
                    return "redirect:http://auth.wuzhishop.com/reg.html";
                }

            }else {
                Map<String,String> errors = new HashMap<>();
                errors.put("code","验证码错误");
//            2.1验证码为空，返回注册页面
                return "redirect:http://auth.wuzhishop.com/reg.html";
            }
        }else {
            Map<String,String> errors = new HashMap<>();
            errors.put("code","验证码过期");
//            验证码为空，返回注册页面
            return "redirect:http://auth.wuzhishop.com/reg.html";
        }
    }

//    注册后进行密码登录
    @PostMapping("/login")
    public String login( UserLoginVo vo, RedirectAttributes redirectAttributes){
//调用shop-member的服务进行登录
        R login = memberFeignService.login(vo);
        if(login.getCode()==0){
//            TODO 登录成功后如何处理
            return "redirect:http://wuzhishop.com";
        }else {
            redirectAttributes.addFlashAttribute("errors","用户名或者手机号不对");
            return "redirect:http://auth.wuzhishop.com/login.html";
        }
    }

}
